package com.yunhe.device.repository.base.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yunhe.common.util.StringUtil;
import com.yunhe.device.domain.base.EquipmentAttributes;
import com.yunhe.device.model.base.EquipmentAttributesQueryCondition;
import org.neo4j.ogm.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @ClassName EquipmentAttributesDao
 * @Description TODO
 * @Author HeTao
 * @Date 2021/7/15 13:01
 * @Version 1.0
 **/
@Repository
public class EquipmentAttributesDao {

    @Autowired
    private Session session;

    public Page<EquipmentAttributes> getEquipmentAttributesByCondition(EquipmentAttributesQueryCondition equipmentAttributesQueryCondition) {
        StringBuffer cql=new StringBuffer();
        //拼接基本语句
        cql.append("MATCH (ea:EquipmentAttributes) WHERE 1=1  and ea.type='01'");
        cql.append(" AND not ea.name  in ['equipLocation','ownedPark','equipName','equipSN']");
        //关键字查询
        if(!StringUtil.isEmpty(equipmentAttributesQueryCondition.getKeywords())){
            cql.append(" AND (ea.name=~'.*"+equipmentAttributesQueryCondition.getKeywords()+".*'");
            cql.append(" or ea.title=~'.*"+equipmentAttributesQueryCondition.getKeywords()+".*')");
        }
        //监测类型查询
        if(!StringUtil.isEmpty(equipmentAttributesQueryCondition.getComponentType())){
            cql.append(" AND ea.componentType='"+equipmentAttributesQueryCondition.getComponentType()+"'");
        }
        int skip=(equipmentAttributesQueryCondition.getPage()-1)*equipmentAttributesQueryCondition.getSize();
        String queryEnd=" RETURN ea" +
                "  order by ea.createTime desc  SKIP "+skip+" LIMIT "+equipmentAttributesQueryCondition.getSize();
        String countEnd=" RETURN count(ea)";

        //分页数据查询结果
        Iterable<EquipmentAttributes> equipmentAttributes = session.query(EquipmentAttributes.class,cql.toString()+queryEnd, Maps.newHashMap());
        //查询总数
        Integer total = session.queryForObject(Integer.class,cql.toString()+countEnd, Maps.newHashMap());

        //封装为分页类
        List<EquipmentAttributes> content= Lists.newArrayList(equipmentAttributes);
        Pageable pageable= PageRequest.of(equipmentAttributesQueryCondition.getPage()-1,equipmentAttributesQueryCondition.getSize());
        Page<EquipmentAttributes> page=new PageImpl<EquipmentAttributes>(content,pageable,total);
        return page;
    }
}
